package org.ling.xuan.config;

import cn.hutool.core.io.FileUtil;
import org.ling.xuan.entity.mo.FileMonitor;
import org.ling.xuan.entity.mo.PropertyFileAlterationObserver;
import org.ling.xuan.util.LxOptional;
import org.ling.xuan.util.LxStrUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class SystemProperties {

    private static final String propertyFilePath = LxStrUtil.unionPath(System.getProperty("user.home")) + "/.lx/application.properties";
    private static final Properties properties = new Properties();
    private static final FileMonitor monitor = new FileMonitor(5000);

    static {
        load();
        monitor.monitor(propertyFilePath, new PropertyFileAlterationObserver() {
            @Override
            public void reload() {
                load();
            }
        });
    }

    private static void load() {
        File file = new File(propertyFilePath);
        FileUtil.mkParentDirs(file);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                throw new RuntimeException("配置文件初始化失败");
            }
        }
        try (InputStreamReader in = new InputStreamReader(new FileInputStream(file),StandardCharsets.UTF_8)) {
            properties.load(in);
        } catch (Exception e) {
            throw new RuntimeException("配置文件导入失败");
        }
    }

    public static Object getOrDefault(SysConstant key, Object value) {
        return properties.getOrDefault(key.getName(), value);
    }

    public static String getOrDefaultStr(SysConstant key, String value) {
        return LxOptional.of(properties, p -> p.getOrDefault(key.getName(), value).toString()).orElse(value);
    }

    public static boolean isTrueDefaultTrue(SysConstant key) {
        return "true".equals(getOrDefaultStr(key, "true"));
    }


    public static boolean isTrueDefaultFalse(SysConstant key) {
        return "true".equals(getOrDefaultStr(key, "false"));
    }
}
